package com.typhoon.condition;

import com.typhoon.condition.group.IConditionGroup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author typhoon
 * @Description TODO
 * @date 2019-11-20 18:01
 * @since V2.0.0
 */



@Service
@Slf4j
public class ConditionFactory implements ApplicationContextAware {


    private static final Map<String, IConditionGroup> map = new HashMap<>();


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        Map<String,IConditionGroup> groupBeans =  applicationContext.getBeansOfType(IConditionGroup.class);
        Map<String,ICondition> conditionBeans = applicationContext.getBeansOfType(ICondition.class);
        groupBeans.forEach((k,v) -> {
            Set<ICondition> conditions = new HashSet<>();
            for(Map.Entry<String,ICondition> entry:conditionBeans.entrySet()) {
                if(entry.getValue().getGroup().contains(k)) {
                    conditions.add(entry.getValue());
                }
            }

            v.setConditions(conditions);
            map.put(v.group(),v);
        });

    }


    public IConditionGroup getGroup(String group) {
        return map.get(group);
    }

}
